<?php


namespace app\api\controller;

use app\api\cache\KeysUtil;
use app\api\cache\RedisCache;
use app\api\logic\CallbackLogic;
use app\api\services\RabbitMqService;
use app\api\services\SandService;
use app\common\controller\RestController;
use app\common\models\Community\CommunityTaskLog;
use app\common\models\Sand\MsgCallback;
use app\common\models\Sand\SandCallback;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class Callback extends RestController
{
    protected $noNeedLogin = ['*'];

    /**
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function wechat(): bool
    {
        $info = CallbackLogic::getInstance()->callback();
        return $this->result($info);
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function alipayCallback(): bool
    {
        $info = CallbackLogic::getInstance()->aliCallback();
        return $this->result($info);
    }

    public function getCallbackOrderNo(): bool
    {
        $orderNo = input('orderNo');
        $info = RedisCache::get(KeysUtil::getOrderCallbackKey($orderNo));
        $data = ['status' => $info ? 1 : 0];
        return $this->result($data);
    }

    /**
     * @throws Exception
     */
    public function sandCallback(): bool
    {
        $param = input();
        SandCallback::getInstance()->insert(['param' => json_encode($param, 256)]);
        $data = SandService::getInstance()->callback();
        return $this->result($data);
    }

    public function advCallback(): bool
    {
        $param = input();
        $secret = 'f4e003588bd043f35b3c08ba8f05c142c2da793df494a524001e19ec670754af:'.$param['trans_id'];
        $sign = hash('sha256',$secret);
        if($sign != $param['sign']){
            return false;
        }
        $extra = !empty($param['extra']) ? json_decode($param['extra'],true) : [];
        $communityId = !empty($extra['communityId']) ? $extra['communityId'] : 0;
        $orderId = !empty($extra['orderId']) ? $extra['orderId'] : 0;
        $event["exchange"] = config('rabbitmq.info_queue');
        $data = [
            'type' => 'task_for_adv',
            'data' => [
                'userId' => $param['user_id'],
                'communityId' => $communityId,
                'orderId' => $orderId
            ]
        ];
        RabbitMqService::send($event, $data);
        return $this->result(true);
    }

    public function msgCallback(): bool
    {
        $param = input();
        MsgCallback::getInstance()->insert(['param' => json_encode($param, 256)]);
        return $this->result(true);
    }
}